<template>
  <div class="app-container">
    <div class="filter-container top">
      <el-input
        v-model="listQuery.goodsName"
        placeholder="商品名"
        style="width: 200px; margin-right: 20px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
      <el-button
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >
        导出
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column type="index" prop="index" label="序号" align="center" width="80"/>

      <el-table-column label="商品名" min-width="150px" prop="goodsName">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.goodsName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="商品价格" min-width="150px" prop="price">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.price }}</span>
        </template>
      </el-table-column>

      <el-table-column label="商品封面" min-width="150px" prop="coverUrl">
        <template slot-scope="{row}">
          <el-image
            style="width: 100px; height: 100px"
            :src="row.coverUrl"
            fit="contain"
            :preview-src-list="[row.coverUrl]"
          />
        </template>
      </el-table-column>

      <el-table-column label="商品描述" min-width="150px" prop="goodsDes">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.goodsDes }}</span>
        </template>
      </el-table-column>

      <el-table-column label="商品类别" min-width="150px" prop="goodsTypeName">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.goodsTypeName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="商品位置" min-width="150px" prop="position">
        <template slot-scope="{row}">
          <el-popover
            v-if="row.goodsLng && row.goodsLat"
            placement="bottom"
            title="位置信息"
            width="500"
            trigger="click"
          >
            <MapShow :markers="[[row.goodsLng, row.goodsLat]]" :center="[row.goodsLng, row.goodsLat]"/>
            <el-button slot="reference" type="text">查看详情</el-button>
          </el-popover>
          <span v-else>无位置信息</span>
        </template>
      </el-table-column>

      <el-table-column label="入手渠道(来源)" min-width="150px" prop="source">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.source }}</span>
        </template>
      </el-table-column>

      <el-table-column label="新旧程度" min-width="150px" prop="depreciationDegree">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.depreciationDegree * 100 + '%' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="发布者" min-width="150px" prop="publisherName">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.publisherName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="上架状态" min-width="150px" prop="status">
        <template slot-scope="{row}">
          <el-switch
            v-if="row.status !== goodsStatus[2].id"
            v-model="row.status"
            :active-value="goodsStatus[0].id"
            :inactive-value="goodsStatus[1].id"
            :active-text="goodsStatus[0].des"
            :inactive-text="goodsStatus[1].des"
            @change="goodsStatusChange($event, row.id)"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
          <span v-else-if="row.status === goodsStatus[2].id" class="link-type">{{ goodsStatus[2].des }}</span>
          <span v-else class="link-type">未知状态</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!=='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.currentPage"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="120px"
        style="width: 500px; margin-left:50px;"
      >
        <el-form-item label="商品名" prop="goodsName">
          <el-input v-model="temp.goodsName"/>
        </el-form-item>

        <el-form-item label="商品价格" prop="price">
          <el-input v-model="temp.price"/>
        </el-form-item>

        <el-form-item label="现有商品封面">
          <el-image
            style="width: 100px; height: 100px"
            :src="tempCoverUrl"
            fit="contain"
            :preview-src-list="[tempCoverUrl]"
          />
        </el-form-item>

        <el-form-item label="商品封面" prop="coverUrl">
          <el-upload
            ref="uploadCover"
            class="upload-demo"
            accept="image/jpeg,image/gif,image/png"
            action=""
            :multiple="false"
            :http-request="uploadFile"
            :data="{oldId: temp.coverUrlId}"
            :limit="1"
            :file-list="cover"
            :on-remove="removeImg"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品描述" prop="goodsDes">
          <el-input v-model="temp.goodsDes" type="textarea" :rows="3"/>
        </el-form-item>

        <el-form-item label="商品类别" prop="goodsType">
          <el-select v-model="temp.goodsType" placeholder="请选择商品类别" clearable class="filter-item">
            <el-option v-for="item in goodsType" :key="item.id" :label="item.type" :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item label="地理位置" prop="position">
          <GaoDeMap :show-geolocation="true" :show-search="true" @position-update="positionUpdate"/>
        </el-form-item>

        <el-form-item label="入手渠道(来源)" prop="source">
          <el-input v-model="temp.source"/>
        </el-form-item>

        <el-form-item label="新旧程度" prop="depreciationDegree">
          <el-input v-model="temp.depreciationDegree"/>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button :disabled="isUploading" @click="handleClose">
          取消
        </el-button>
        <el-button type="primary" :disabled="isUploading" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { changeGoodsStatus, goodsRestfull, queryAdminGoodsList } from '@/api/goods'
import { goodsTypeRestfull } from '@/api/goods-type'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import { uploadFile, removeFile } from '@/api/file'
import UUID from '@/utils/uuid'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import GaoDeMap from '@/components/GaoDeMap'
import MapShow from '@/components/GaoDeMap/MapShow'

export default {
  name: 'Goods',
  components: { GaoDeMap, MapShow, Pagination },
  directives: { waves },
  filters: {
    parseTime
  },
  data() {
    const validatePrice = (rule, value, callback) => {
      value += ''
      if (!value) {
        callback(new Error('商品价格不能为空'))
      } else if (value.indexOf('.') !== -1 && value.split('.').length > 2) {
        callback(new Error('请输入正确格式的金额')) // 防止输入多个小数点
      } else if (value.indexOf('.') !== -1 && value.split('.')[1].length > 2) {
        callback(new Error('请输入正确的小数位数(小数点后两位)')) // 小数点后两位
      } else {
        callback()
      }
    }

    return {
      goodsType: [],
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
        pageSize: 10,
        goodsName: undefined
      },
      temp: {
        id: undefined,
        goodsName: undefined,
        price: 0.00,
        coverUrlId: undefined,
        // coverUrl: undefined,
        goodsDes: undefined,
        goodsType: undefined,
        goodsLng: undefined,
        goodsLat: undefined,
        source: undefined,
        depreciationDegree: 1
      },
      tempCoverUrl: undefined,
      isUploading: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加商品'
      },
      rules: {
        goodsName: [{ required: true, message: '商品名不能为空', trigger: 'change' }],
        price: [{
          trigger: 'blur',
          message: '价格设置有误',
          required: false,
          validator: validatePrice
        }]
      },
      downloadLoading: false,
      cover: [],
      showGoodsPosition: false,
      goodsStatus: [{
        id: 0,
        des: '上架'
      }, {
        id: 1,
        des: '下架'
      }, {
        id: 2,
        des: '已售出'
      }]
    }
  },
  created() {
    this.getList()
    this.getGoodsType()
  },
  methods: {
    getList() {
      this.listLoading = true
      queryAdminGoodsList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    getGoodsType() {
      goodsTypeRestfull.fetchAll(this.listQuery).then(response => {
        this.goodsType = response.data
      })
    },
    handleFilter() {
      this.listQuery.currentPage = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        goodsName: undefined,
        price: 0.00,
        coverUrlId: undefined,
        // coverUrl: undefined,
        goodsDes: undefined,
        goodsType: undefined,
        goodsLng: undefined,
        goodsLat: undefined,
        source: undefined,
        depreciationDegree: 1
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          goodsRestfull.createData(this.temp).then(response => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            this.total += 1
            this.$refs.uploadCover.clearFiles()
            this.$notify({
              title: '成功',
              message: '商品添加成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.tempCoverUrl = row.coverUrl
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$refs.uploadCover.clearFiles()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          goodsRestfull.updateData(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '商品信息更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        goodsRestfull.removeData(row.id).then(() => {
          this.list.splice(index, 1)
          this.total -= 1
          this.$notify({
            title: '成功',
            message: '商品信息已删除',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/utils/excel-export').then(exportExcel => {
        const tHeader = {
          id: 'id',
          goodsName: '商品'
        }
        exportExcel.exportExcel(tHeader, this.list, 'goodsName')
      })
      this.downloadLoading = false
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    handleClose(done) {
      if (this.dialogStatus === 'create' && this.temp.coverUrlId) {
        // 移除临时上传但未提交的商品图片
        removeFile(this.temp.coverUrlId)
      }
      this.$refs.uploadCover.clearFiles()
      this.dialogFormVisible = false
      if (done && typeof (done) === 'function') {
        done()
      }
    },
    removeImg(file) {
      console.log(file)
    },
    uploadFile({ file, data, onError, onSuccess }) {
      this.isUploading = true
      uploadFile({
        fileName: file.name,
        tag: 'goods',
        secondaryTag: UUID(),
        des: `商品图片-${file.name}`
      }, file).then(res => {
        // 移除旧的图片(如果存在)
        if (data.oldId) {
          removeFile(data.oldId)
        }
        this.temp.coverUrlId = res.data.id
        // this.temp.coverUrl = res.data.fileFullPath
        this.isUploading = false
        onSuccess()
      }).catch(err => {
        onError(err)
        this.$notify({
          title: '失败',
          message: '图片上次失败',
          type: 'error',
          duration: 2000
        })
        this.$refs.uploadCover.clearFiles()
        this.isUploading = false
      })
    },
    positionUpdate(e) {
      console.log('hhh, ', e)
      this.temp.goodsLng = e.position[0]
      this.temp.goodsLat = e.position[1]
    },
    goodsStatusChange(status, id) {
      changeGoodsStatus({ id, status }).then(_ => {
        this.$notify({
          title: '成功',
          message: '商品状态修改成功',
          type: 'success',
          duration: 2000
        })
      }).catch(_ => {
        this.$notify({
          title: '失败',
          message: '商品状态修改失败',
          type: 'error',
          duration: 2000
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-button--mini {
  padding: 7px 10px;
  min-width: 60px;
}

.top {
  margin-bottom: 20px;
}

#map {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 200px;
}
</style>
